package com.an.pay.task;

import com.an.pay.client.WxPayClient;
import com.an.pay.enums.OrderStatus;
import com.an.pay.enums.PayType;
import com.an.pay.enums.WxTradeState;
import com.an.pay.service.OrderInfoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.an.pay.entity.OrderInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class WxPayTask {

    @Autowired
    private WxPayClient wxPayRequestClient;
    @Autowired
    private OrderInfoService orderInfoService;

    /**
     *  检查订单的状态
     *      - 订单支付成功但异步通知未接收到
     *      - 支付超时未支付，关闭订单
     * @throws IOException
     */
    @Scheduled(cron = "0/60 * * * * ?")
    public void CheckOrderStatus() throws IOException {
        log.info("进入微信CheckOrderStatus");
        List<OrderInfo> orderInfoList = orderInfoService.getNoPayOrderByDuration(1, PayType.WXPAY.getType());
        for (OrderInfo orderInfo : orderInfoList) {
            // 查询当前订单状态，返回数据
            Map<String, Object> orderNoStatus = wxPayRequestClient.findOrderNoStatus(orderInfo.getOrderNo());
            log.info("orderStatus==={}",orderNoStatus);
            //订单未支付
            if(orderNoStatus.get("trade_state").equals(WxTradeState.NOTPAY.getType())){
                //关闭订单
                wxPayRequestClient.closeOrder(orderInfo.getOrderNo());
                // 修改订单状态
                OrderInfo order= new OrderInfo();
                order.setOrderStatus(OrderStatus.CLOSED.getType());
                orderInfoService.update(order,new QueryWrapper<OrderInfo>().eq("order_no",orderInfo.getOrderNo()).eq("payment_type",PayType.WXPAY.getType()));
            }else if(orderNoStatus.get("trade_state").equals(WxTradeState.SUCCESS.getType())){
                //订单支付成功
                //修改订单支付状态
                OrderInfo order= new OrderInfo();
                order.setOrderStatus(OrderStatus.SUCCESS.getType());
                orderInfoService.update(order,new QueryWrapper<OrderInfo>().eq("order_no",orderInfo.getOrderNo()).eq("payment_type",PayType.WXPAY.getType()));
            }else if(orderNoStatus.get("trade_state").equals(WxTradeState.CLOSED.getType())){
                // 修改订单状态
                OrderInfo order= new OrderInfo();
                order.setOrderStatus(OrderStatus.CLOSED.getType());
                orderInfoService.update(order,new QueryWrapper<OrderInfo>().eq("order_no",orderInfo.getOrderNo()).eq("payment_type",PayType.WXPAY.getType()));
            }


        }

    }
}
